from maptile import *

class MapLayer:
    attrs = ["tile_width", "tile_height", "tiles", "sprites"]

    def __init__(self, tile_width, tile_height):
        self.tile_width = tile_width
        self.tile_height = tile_height
        self.tiles = []
        self.sprites = []
        self.tile_dict = {}
        self.sprite_dict = {}

    def add_tile(self, x, y, tile, tile_id):
        key = "%s,%s" % (x, y)
        if key not in self.tile_dict.keys():
            maptile = MapTile(x, y, tile, tile_id)
            self.tiles.append(maptile)
            self.tile_dict[key] = maptile

    def add_sprite(self, x, y, sprite, sprite_id):
        key = "%s,%s" % (x, y)
        if key not in self.sprite_dict.keys():
            maptile = MapTile(x, y, sprite, sprite_id)
            self.sprites.append(sprite)
            self.sprite_dict[key] = maptile

    def remove_tile(self, x, y):
        key = "%s,%s" % (x, y)
        if key in self.tile_dict.keys():
            maptile = self.tile_dict[key]
            self.tiles.remove(maptile)
            del self.tile_dict[key]

    def remove_sprite(self, x, y):
        key = "%s,%s" % (x, y)
        if key in self.sprite_dict.keys():
            maptile = self.sprite_dict[key]
            self.sprites.remove(maptile)
            del self.sprite_dict[key]

    def todict(self):
        dict = {}
        for attr in MapLayer.attrs:
            if attr == "tiles":
                dict[attr] = []
                for tile in self.tiles:
                    dict[attr].append(tile.todict())
            elif attr == "sprites":
                dict[attr] = []
                for sprite in self.sprites:
                    dict[attr].append(sprite.todict())
            else:
                dict[attr] = getattr(self, attr, None)

        return dict
